package wkt.auth;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import net.xnzn.framework.config.exception.BizRuntimeException;
import net.xnzn.framework.secure.AccessToken;
import net.xnzn.framework.secure.filter.before.security.SmUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.SortedMap;

@RestController
@RequestMapping("/pc/auth")
public class PcUserController {
    @Autowired
    private PcUserMapper pcUserMapper;

    @PostMapping("/login")
    public String login(@Valid @RequestBody PcUser param) {
        final PcUser user = pcUserMapper.selectOne(Wrappers.lambdaQuery(PcUser.class).eq(PcUser::getUsername, param.getUsername()));
        if (user == null) throw new BizRuntimeException("用户名/密码错误");
        SortedMap<String, String> data = Maps.newTreeMap();
        data.put("password", param.getPassword());
        if (!user.getPassword().equals(SmUtils.signBySm3WithServerKey(data,"clientKey"))) {
            throw new BizRuntimeException("用户名/密码错误");
        }
        AccessToken token = AccessToken.create(user.getId(), user.getUsername()).authenticate().store();
        return token.getId();
    }
}
